function idx_input(o)
{
    var e = {};
    var l = o.find('input,select');
    for(i = 0; i < l.length; i++) {
        var nz = $(l[i]).attr('name');
        var c = e[nz];
        if(c === undefined) c = e[nz] = [];
        c.push(l[i]);
    }
    
    var k = {};
    for(var nz in e) k[nz] = $(e[nz]);
    
    o.data('es', k);
}


function upd_ui_edit_cart_item()
{
    var ctx = g_v_usr_edit_cart_item.data('ctx');
    
    var qty = parseInt(ctx.v_qty.val()) || 0;
    $(ctx.v_cds[3]).text('Total: $' + (qty * ctx.price).toFixed(2) );
}

function confirm_edit()
{
    var r = $(this).data('js');
    var ctx = g_v_usr_edit_cart_item.data('ctx');
    
    $(ctx.v_cds[0]).text( (parseInt(r.idx/10) + 1) + '. ' + r.item[1] );
    var price = r.item[0] || 0;
    ctx.price = price;
    
    $(ctx.v_cds[1]).text('$' + price.toFixed(2) + ' / ea');
    ctx.v_qty.val(r.qty).change();
    
    g_v_usr_edit_cart_item.data('m_id', r.idx).popup('open');
    
    return false;
}

function upd_ui_popup_order()
{
    var ctx = g_v_usr_popup_order.data('ctx');
    
    var qty = parseInt(ctx.v_qty.val()) || 0;
    $(ctx.v_cds[3]).text('Total: $' + (qty * ctx.price).toFixed(2) );
}

function confirm_add(id)
{
    var o = $(this);
    
    var ctx = g_v_usr_popup_order.data('ctx');
    
    var cds = o.children('span');
    $(ctx.v_cds[0]).text( $(cds[0]).text() );
    var price = parseFloat( $(cds[1]).text().substring(1) ) || 0;
    ctx.price = price;
    
    $(ctx.v_cds[1]).text('$' + price.toFixed(2) + ' / ea');
    ctx.v_qty.val(1).change();
    
    g_v_usr_popup_order.data('m_id', id).popup('open');
    
    return false;
}

function call_cart(action_id, item_id, args, cb)
{
    var data = {item_id:item_id};
    $.extend(data, args || {});
    
    $.ajax({
        async: false,
        type: 'post',
        url: 'cart.php?action_id=' + action_id,
        data: data,
        success: function(cjs) {
            cb(cjs);
        },
        dataType: 'json'
    });
    
}

function update_cart_total_cb(cjs)
{
    if(cjs.lst_len) {
        g_v_btn_view_cart.text('$' + cjs.sub_total.toFixed(2));
        
    } else {
        g_v_btn_view_cart.text('$0.00');
    }
}

function update_cart_total()
{
    call_cart(0, 0, {'mini': 1}, update_cart_total_cb);
}

function update_cart_cb(cjs)
{
    var l = [];
    for(var i = 0; i < cjs.lst.length; i++) {
        var r = cjs.lst[i];
        l.push(
               $('<tr></tr>').data('js', r).click(confirm_edit)
               .append( $('<td></td>').text( (parseInt(r.idx/10) + 1) + '. ' + r.item[1]) )
               .append( $('<td></td>').text(r.qty) )
               .append( $('<td></td>').text('$'+r.ex_price.toFixed(2)) )
        );
    }
    g_v_cart_item_list.children('tbody').empty().append(l);
    
    var v_f = g_v_cart_item_list.children('tfoot').find('>tr >td:nth-child(2)');
    if(cjs.lst.length) {
        $(v_f[0]).text( cjs.ajs.tip ? '$' + cjs.ajs.tip.toFixed(2) : '' );
        $(v_f[1]).text( '$' + cjs.oa_total.toFixed(2));
        g_v_cart_item_list_popup_extra.find('[name="tip"]').val( cjs.ajs.tip ? cjs.ajs.tip : '' );
        
    } else {
        v_f.text('');
    }
    
    g_v_cart_item_list.table("rebuild");
    update_cart_total_cb(cjs);
}

function update_cart()
{
    call_cart(0, 0, null, update_cart_cb);
}

function on_sel_checkout()
{
    var t = $(this).val();

}

function is_cart_empty()
{
    return !g_v_cart_item_list.children('tbody').children().length;
}

function is_phone_number(s)
{
    return /^[0-9()\- ]+$/.test(s);
}

function is_email(s)
{
    return /^[\w.\-]+@[\w.\-]+$/.test(s);
}

function mark_label_error(v)
{
    v.closest('.ui-field-contain').find('label').addClass('field_error');
}

function validate_card(ci)
{
    return ci;
}

function submit_order()
{
    var es;
    var acct_id, acct_passwd;
    
    if(g_v_co_account_info.is(':visible')) {
        g_v_co_account_info.find('label').removeClass('field_error');
        es = g_v_co_account_info.data('es');
        acct_id = $.trim(es.phone_or_email.val());
        acct_passwd = $.trim(es.passwd.val());
        if(acct_id) {
            if( !is_email(acct_id) && !is_phone_number(acct_id) ) { mark_label_error(es.phone_or_email); return; }
            if(acct_passwd.length < 4) { mark_label_error(es.passwd); return; }
        }
    }
    
    g_v_co_order_info.find('label').removeClass('field_error');
    es = g_v_co_order_info.data('es');
    
    var order_info = {
        type: es.type.filter(':checked').val(),
        name: $.trim(es.name.val()),
        phone: $.trim(es.phone.val()),
        address: $.trim(es.address.val()),
        comment: $.trim(es.comment.val()),
    };
    if(!order_info.name) { mark_label_error(es.name); return; }
    if(!is_phone_number(order_info.phone)) { mark_label_error(es.phone); return; }
    if(order_info.type === 'delivery') {
        if(!order_info.address) { mark_label_error(es.address); return; }
    } else order_info.address = '';
    
    
    es = g_v_co_payment_info.data('es');
    var card_info = {
        name: es.name.val(),
        address: es.address.val(),
        number: es.number.val(),
        code: es.code.val(),
        month: es.month.val(),
        year: es.year.val(),
    };

    card_info = validate_card(card_info);
    
    var js = {
        acct_id: acct_id,
        acct_passwd: acct_passwd,
        card_info: card_info,
        order_info: order_info,
    }
    
    $.ajax({
        async: false,
        type: 'post',
        url: 'order.php',
        data: {'js':JSON.stringify(js)},
        success: function(cjs) {
            cb(cjs);
        },
        dataType: 'json'
    });
    
}


function reset_checkout_form()
{
    g_v_co_btn_login.show();
    g_v_co_account_info.show();
    
    var vs = g_v_co_account_info.data('es');
    for(var k in vs) if(vs[k].attr('type') !== 'radio') vs[k].val('');
    
    var vs = g_v_co_order_info.data('es');
    for(var k in vs) if(vs[k].attr('type') !== 'radio') vs[k].val('');
    
    $(vs.type[1]).prop('checked', true);
    vs.type.checkboxradio('refresh');
    
    var vs = g_v_co_payment_info.data('es');
    for(var k in vs) if(vs[k].attr('type') !== 'radio') vs[k].val('');
}


function get_user_record_cb(js)
{
    update_cart_total_cb(js);
    
    reset_checkout_form();
    
    var es;
    if(js.user.id) {
        g_v_co_btn_login.hide();
        g_v_co_account_info.hide();
        
        var oi = js.user.order_info || {};
        es = g_v_co_order_info.data('es');
        es.name.val(oi.name || '');
        es.phone.val(oi.phone || '');
        es.address.data('ov', oi.address || '').val(oi.address || '');
        es.type.filter('[value="'+(oi.type || 'delivery')+'"]').prop('checked', true).change();
        es.type.checkboxradio('refresh');
        
        var ci = js.user.card_info || {};
        es = g_v_co_payment_info.data('es');
        es.name.val(ci.name || '');
        es.address.val(ci.address || '');
        es.number.data('ov', ci.number || '').val(ci.number || '').change();
    }
    
}

function get_user_record()
{
    call_cart(0, 0, {'mini': 1, 'user_record': 1}, get_user_record_cb);
}

function login_cb(js)
{
    update_cart_total_cb(js);
    
    if(!js.user.id) {
        g_v_login_form_msg.html('wrong username or password!');
        return;
    }
    
    $.mobile.changePage(g_last_page_id ? '#' + g_last_page_id : '');
}

function login()
{
    var es = g_v_login_form.data('es');
    var phone_or_email = $.trim(es.phone_or_email.val());
    var passwd = $.trim(es.passwd.val());
    
    es.passwd.val('');
    g_v_login_form_msg.html('&nbsp');
    
    if(!phone_or_email || !passwd) return;
    
    call_cart(0, 0, {'mini': 1, 'user_acct': phone_or_email, 'user_passwd': passwd}, login_cb);
}

function check_if_login_cb(js)
{
    update_cart_total_cb(js);
    if(js.user.id) return;
    $.mobile.changePage('#page_login');
}

function check_if_login()
{
    call_cart(0, 0, {'mini': 1}, check_if_login_cb);
}

function load_recent_orders_cb(js)
{
    var v = $('#page_my_account .ui-content').empty();
    
    var lst = [];
    for(var i = 0; i < js.length; i++) {
        var r = js[i];
        lst.push(
            $('<div data-role="listview" data-inset="true"></div>')
            .append('<li data-role="list-divider">'+r.dt+'  #'+r.id+' <span class="ui-li-count">$'+r.total.oa_total.toFixed(2)+'</span></li>').listview()
        );
    }
    console.log('---');
    v.append(lst);
}

function load_recent_orders()
{
    $.get('my_account.php', load_recent_orders_cb, 'json');
}

function logout()
{
    $.post('logout.php', {'a': 1}, check_if_login, 'json');
}

//global call
var __g_ready = 0;
function g_ready() {
    if(__g_ready) return;
    __g_ready = 1;
    
    $("body >[data-role='panel']").enhanceWithin().panel();
    $("body >[data-role='header']").toolbar();
    
    g_v_btn_view_cart = $('#btn_view_cart');
    update_cart_total();
};


var g_pagecreate_cbs = {};
var g_pageview_cbs = {};

g_pagecreate_cbs['page_place_order'] = function() {

$('#page_place_order').find('ul[data-role="listview"]').on("filterablefilter", function(event, ui) {
    if(ui.items.length != ui.items.filter('.ui-screen-hidden').length)
        $(this).closest('[data-role="collapsible"]').show();
    else
        $(this).closest('[data-role="collapsible"]').hide();
});

g_v_usr_popup_order = $('#usr_popup_order');
var ctx = {
    'v_cds': g_v_usr_popup_order.find('[data-role="main"]').children(),
    'v_qty': g_v_usr_popup_order.find('input[name="inp_qty"]').change(upd_ui_popup_order)
};
g_v_usr_popup_order.data('ctx', ctx);

g_v_usr_popup_order.find('a.ui-icon-back').click(function() { g_v_usr_popup_order.popup('close'); return false; });
g_v_usr_popup_order.find('a.ui-icon-check').click(function() {
    var ctx = g_v_usr_popup_order.data('ctx');
    var args = {
        'qty': parseInt(ctx.v_qty.val()),
        'mini': 1
    };
    call_cart(2, g_v_usr_popup_order.data('m_id'), args, update_cart_total_cb);
    
    g_v_usr_popup_order.popup('close');
    return false;
});

};

g_pagecreate_cbs['page_view_cart'] = function() {

g_v_usr_edit_cart_item = $('#usr_edit_cart_item');
var ctx = {
    'v_cds': g_v_usr_edit_cart_item.find('[data-role="main"]').children(),
    'v_qty': g_v_usr_edit_cart_item.find('input[name="inp_qty"]').change(upd_ui_edit_cart_item)
};
g_v_usr_edit_cart_item.data('ctx', ctx);

g_v_usr_edit_cart_item.find('[data-role="main"] a.ui-icon-delete').click(function() {
    call_cart(20, g_v_usr_edit_cart_item.data('m_id'), null, update_cart_cb);
    
    g_v_usr_edit_cart_item.popup('close');
    return false;
});
g_v_usr_edit_cart_item.find('a.ui-icon-check').click(function() {
    var ctx = g_v_usr_edit_cart_item.data('ctx');
    var args = {
        'qty': parseInt(ctx.v_qty.val()),
    };
    call_cart(1, g_v_usr_edit_cart_item.data('m_id'), args, update_cart_cb);
    
    g_v_usr_edit_cart_item.popup('close');
    return false;
});

g_v_cart_clear_confirm = $('#cart_clear_confirm');
$('a.ui-icon-check', g_v_cart_clear_confirm).click(function() {
    call_cart(255, 0, null, update_cart_cb);
    g_v_cart_clear_confirm.popup('close');
    return false;
});

g_v_cart_item_list = $('#cart_item_list');
g_v_cart_item_list_popup_extra = $('#cart_item_list_popup_extra')
g_v_cart_item_list.children('tfoot').click(function() {
    g_v_cart_item_list.children('tbody').children().length && g_v_cart_item_list_popup_extra.popup('open');
});

g_v_cart_item_list_popup_extra.find('a.ui-icon-check').click(function() {
    call_cart(200, 0, {'tip': g_v_cart_item_list_popup_extra.find('[name="tip"]').val()}, update_cart_cb);
    g_v_cart_item_list_popup_extra.popup('close');
    return false;
});

};

g_pagecreate_cbs['page_check_out'] = function() {

g_v_co_order_info = $('#co_order_info'); idx_input(g_v_co_order_info);
var es = g_v_co_order_info.data('es');
es.type.change(function() {
    var o = $(this);
    if(!o.is(':checked')) return;
    var es = g_v_co_order_info.data('es');
    var nz = o.val();
    if(nz === 'delivery') {
        es.address.closest('.ui-field-contain').show();
    } else {
        es.address.closest('.ui-field-contain').hide();
    }
    
});
es.address.change(function() {
    var es = g_v_co_order_info.data('es');
    if(es.address.data('ov') !== $.trim(es.address.val())) {
        var ci_es = g_v_co_payment_info.data('es');
        if(ci_es.number.val().indexOf('*') >= 0) ci_es.number.val('').change();
    }
});

g_v_co_btn_login = $('#co_btn_login');

g_v_co_account_info = $('#co_account_info'); idx_input(g_v_co_account_info);
g_v_co_payment_info = $('#co_payment_info'); idx_input(g_v_co_payment_info);
var es = g_v_co_payment_info.data('es');
es.number.change(function() {
    var es = g_v_co_payment_info.data('es');
    var oi_es = g_v_co_order_info.data('es');
    
    var ov = es.number.data('ov');
    if(ov && $.trim(es.number.val()) === ov) {
        es.name.closest('.ui-field-contain').hide();
        es.address.closest('.ui-field-contain').hide();
        es.month.closest('.ui-field-contain').hide();
        
        if(oi_es.type.filter(':checked').val() === 'pickup')
            es.code.closest('.ui-field-contain').show();
        else
            es.code.closest('.ui-field-contain').hide();
        
    } else {
        es.name.closest('.ui-field-contain').show();
        es.address.closest('.ui-field-contain').show();
        es.code.closest('.ui-field-contain').show();
        es.month.closest('.ui-field-contain').show();
        
    }
    
});

g_v_btn_submit_order = $('#btn_submit_order').click(submit_order);

};

g_pagecreate_cbs['page_login'] = function() {
$('#login_btn_login').click(login);
g_v_login_form = $('#login_form'); idx_input(g_v_login_form);
g_v_login_form_msg = $(g_v_login_form.children('li')[3]);
};

g_pagecreate_cbs['page_my_account'] = function() {
var co = $(this);

$('.m_footer_my_account .ui-icon-power', co).click(logout);

};


g_pageview_cbs['page_view_cart'] = function() {
update_cart();
};

g_pageview_cbs['page_my_account'] = function() {
check_if_login();
load_recent_orders();
};

g_pageview_cbs['page_check_out'] = function() {
get_user_record();
};


$(document).on("pagecreate", function(event){
    g_ready();
    
    var id = $(event.target).attr('id');
    //console.log('pagecreate - ' + id);
    id && g_pagecreate_cbs[id] && g_pagecreate_cbs[id].call(event.target, event);
});

var g_last_page_id = null;
$(document).on("pageshow", function(event, ui){
    var id = $(event.target).attr('id');
    //console.log('pageview - ' + id);
    g_last_page_id = ui.prevPage.attr('id');
    id && g_pageview_cbs[id] && g_pageview_cbs[id].call(event.target, event);
    
});


